<?php

namespace addons\facrm\controller\facrm\business;

use addons\facrm\library\BackendApi;
use app\admin\model\facrm\Customer;

use think\Db;


/**
 * 联系人
 */
class Contacts extends BackendApi
{

    protected $model = null;
    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'customer_id,name,mobile,telephone';
    protected $childrenAdminIds = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('\app\admin\model\facrm\business\Contacts');
        $this->request->filter(['strip_tags']);
    }

    /**
     * 联系人列表[商机]
     * @ApiParams(name="business_id", type="int", required=true, description="商机id")
     */
    public function index()
    {
        $business_id = $this->request->request("business_id");
        $filter_w = ['business_id'=>$business_id];

        $auth = new \addons\facrm\library\Auth();
        if (!$auth->checkBusinessAuth($business_id, $this->auth)) {
            $this->error(__('您没有权限'));
        }

        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('keyField')) {
            $this->request->request(['custom' => $filter_w]);
            return $this->selectpage();
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        $list = $this->model
            ->where($where)
            ->where($filter_w)
            ->with([
                'contact'
            ])
            ->order($sort, $order)
            ->limit($offset, $limit)->fetchSql(false)
            ->select();
        $result = array( "rows" => $list);
        return $this->success('', $result);


    }

    /**
     * 关联联系人
     * @ApiMethod (POST)
     * @ApiParams(name="contacts_ids", type="string", required=true, description="联系人ID，多个逗号隔开")
     * @ApiParams(name="business_id", type="int", required=true, description="商机id")
     */
    public function correlation()
    {
        //关联提交
        $contacts_ids = $this->request->post("contacts_ids");
        $business_id = $this->request->post("business_id");
        if (!$business_id) $this->error(__("商机信息参数不存在"));
        $businessModel = model('\app\admin\model\facrm\Business');
        $row = $businessModel->get($business_id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if (!$this->auth->checkBusinessAuth($row,$this->auth)) {
            $this->error(__('You have no permission'));
        }
        //查询客户联系人的合法性
        $row_c = Customer::get($row['customer_id'], ['contacts' => function ($contacts) use ($contacts_ids) {
            $contacts->where('id', 'in', $contacts_ids);
        }]);
        if (!$row_c->contacts) {
            $this->error(__('选择的联系方式不存在'));
        }
        $insert_data = [];
        foreach ($row_c->contacts as $r) {
            $temp['business_id'] = $business_id;
            $temp['contacts_id'] = $r->id;
            $insert_data[] = $temp;
        }
        $this->model->saveAll($insert_data);
        $this->success(__("关联成功"));
    }


    /**
     * 删除关联联系人
     * @ApiMethod (POST)
     * @ApiParams(name="ids", type="int", required=true, description="关联联系人ids,多个用逗号隔开")
     * @ApiParams(name="business_id", type="int", required=true, description="商机ID")
     */
    public function del()
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $this->request->post("ids");
        $business_id = $this->request->post("business_id");

        if (!$this->auth->checkBusinessAuth($business_id,$this->auth)) {
            $this->error(__('You have no permission'));
        }

        if ($ids) {
            $pk = $this->model->getPk();
            $list = $this->model->where($pk, 'in', $ids)->where('business_id',$business_id)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success(__("删除成功"));
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
